import akshare as ak

import pandas as pd


def get_marco_data():
    df = pd.DataFrame(columns=["Year", "Quarter", "GDPg"])

    gdp_df = ak.macro_china_gdp()
    for _, row in gdp_df.iterrows():
        date, _, value, *_ = row
        df.loc[len(df)] = [int(date[:4]), {
            "第1季度": 1,
            "第1-2季度": 2,
            "第1-3季度": 3,
            "第1-4季度": 4,
        }[date[5:]], value]

    df = df[df["Year"] >= 2020]

    cpi_df = ak.macro_china_cpi()
    cpi_df['Month'] = pd.to_datetime(cpi_df['月份'].str.replace('年', '-').str.replace('月份', ''), format='%Y-%m')
    cpi_df['Year'] = cpi_df['Month'].dt.year
    cpi_df['Quarter'] = cpi_df['Month'].dt.quarter
    quarter_cpi_df = cpi_df.groupby(['Year', 'Quarter'])['全国-同比增长'].mean().reset_index()
    quarter_cpi_df = quarter_cpi_df.rename(columns={"全国-同比增长": "CPIg"})
    quarter_cpi_df = quarter_cpi_df[quarter_cpi_df["Year"] >= 2020]

    df = df.merge(quarter_cpi_df, on=['Year', 'Quarter'], how='left')

    ppi_df = ak.macro_china_ppi()
    ppi_df['Month'] = pd.to_datetime(ppi_df['月份'].str.replace('年', '-').str.replace('月份', ''), format='%Y-%m')
    ppi_df['Year'] = ppi_df['Month'].dt.year
    ppi_df['Quarter'] = ppi_df['Month'].dt.quarter
    quarter_ppi_df = ppi_df.groupby(['Year', 'Quarter'])['当月同比增长'].mean().reset_index()
    quarter_ppi_df = quarter_ppi_df.rename(columns={"当月同比增长": "PPIg"})
    quarter_ppi_df = quarter_ppi_df[quarter_ppi_df["Year"] >= 2020]

    df = df.merge(quarter_ppi_df, on=['Year', 'Quarter'], how='left')
    df["date"] = df["Year"].apply(lambda x: f"{x:.0f}") + "-" + df["Quarter"].apply(lambda x: f"{x * 3:0>2.0f}")
    del df["Quarter"]
    del df["Year"]

    df = df.round(2)

    return df


if __name__ == '__main__':
    print(get_marco_data())
